<?php
if (! defined ( 'IN_ADMIN' )) {
	exit ( 'Access Denied' );
}

//判断当前用户登录状态
function checkauth() {
	global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN;
	if($_SCOOKIE['auth']) {
		@list($password, $uid) = explode("\t", authcode($_SCOOKIE['auth'], 'DECODE'));
		$_SGLOBAL['supe_uid'] = intval($uid);
		if($password && $_SGLOBAL['supe_uid']) {
			$data = $_SESSION['user'] ;
			$user = $data['resultData'] ;
			if($user && $data['token'] && $data['token'] == $password){
				$_SGLOBAL['supe_username'] = $user['userInfo']['account'];
				$_SGLOBAL['supe_uid'] = $user['userInfo']['uid'];
				$_SGLOBAL['token'] = $data['token'];
				$_SGLOBAL['member'] = $user;
				$_SGLOBAL['adminuids'] = $_SESSION['adminuids'];
			}else {
				$_SGLOBAL['supe_uid'] = 0;
			}
		}
	}
	if(empty($_SGLOBAL['supe_uid'])) {
		clearcookie();
	} else {
		$_SGLOBAL['username'] = $user['userInfo']['nickname'];
	}
	//添加测试
	$_SGLOBAL['adminuids'][] = "3894301";
	$_SGLOBAL['adminuids'][] = "3899627";

}

//清空cookie
function clearcookie() {
	global $_SGLOBAL;

	obclean();
	ssetcookie('auth', '', -86400 * 365);
	$_SGLOBAL['supe_uid'] = 0;
	$_SGLOBAL['supe_username'] = '';
	$_SGLOBAL['member'] = array();
}

//cookie设置
function ssetcookie($var, $value, $life=0) {
	global $_SGLOBAL, $_SC, $_SERVER;
	setcookie($_SC['cookiepre'].$var, $value, $life?($_SGLOBAL['timestamp']+$life):0, $_SC['cookiepath'], $_SC['cookiedomain'], $_SERVER['SERVER_PORT']==443?1:0);
}

// SQL ADDSLASHES
function saddslashes($string) {
	if (is_array ( $string )) {
		foreach ( $string as $key => $val ) {
			$string [$key] = saddslashes ( $val );
		}
	} else {
		$string = addslashes ( $string );
	}
	return $string;
}

// 取消HTML代码
function shtmlspecialchars($string) {
	if (is_array ( $string )) {
		foreach ( $string as $key => $val ) {
			$string [$key] = shtmlspecialchars ( $val );
		}
	} else {
		$string = preg_replace ( '/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1', str_replace ( array (
				'&',
				'"',
				'<',
				'>' 
		), array (
				'&amp;',
				'&quot;',
				'&lt;',
				'&gt;' 
		), $string ) );
	}
	return $string;
}

//处理搜索关键字
function stripsearchkey($string) {
	$string = trim($string);
	$string = str_replace('*', '%', addcslashes($string, '%_'));
	$string = str_replace('_', '\_', $string);
	return $string;
}


//字符串解密加密
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

	$ckey_length = 4;	// 随机密钥长度 取值 0-32;
	// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	// 当此值为 0 时，则不产生随机密钥

	$key = md5($key ? $key : "hushuhfihdsifhdsi");
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

function request($key =   NULL)/*{{{*/
{
    if (!isset($_REQUEST[$key]) &&  empty($key))
    {
        $result     =   $_REQUEST;
    }
    else
    {
        if (isset($_REQUEST[$key]))
            $result =   $_REQUEST[$key];
        else
            $result =   NULL;
    }

    return  $result;
}

//static
function register_static($file){
    global $_SC;
    return  $_SC['static_url'].$file."?v=".$_SC['static_version'];
}

function render_bak ($tpl, $data) {
    // 从数组中把变量导入到当前的符号表中
    extract($data, EXTR_SKIP);

    // 使用全局变量
    global $_SGLOBAL;

    // 开始输出缓冲, 这时PHP停止输出, 在这以后的输出都被转到一个内部的缓冲里.
    ob_start();

    try {
        // 加载本地模板
        include template($tpl);
    } catch (Exception $e) {
        // 删除输出缓冲区
        ob_end_clean();

        // 抛出异常
        throw $e;
    }

    // 结束输出缓冲, 并扔掉缓冲里的内容.
    return ob_get_clean();
}

function render ($tpl, $data) {
    // 从数组中把变量导入到当前的符号表中
    extract($data, EXTR_SKIP);

    // 使用全局变量
    global $_SGLOBAL;

    // 开始输出缓冲, 这时PHP停止输出, 在这以后的输出都被转到一个内部的缓冲里.
    ob_start();

    try {
        // 加载本地模板
        include template_v2($tpl);
    } catch (Exception $e) {
        // 删除输出缓冲区
        ob_end_clean();

        // 抛出异常
        throw $e;
    }

    // 结束输出缓冲, 并扔掉缓冲里的内容.
    return ob_get_clean();
}

// 模板调用
function template_v2($name) {
    $tpl = "template/admin_v2/$name";
    $objfile = S_ROOT . './data/tpl_cache/' . str_replace ( '/', '_', $tpl ) . '.php';
    if (! file_exists ( $objfile ) ||2>1) {
        include_once (S_ROOT . './source/function_template.php');
        parse_template ( $tpl );
    }

    return $objfile;
}

// 模板调用
function template($name) {
	if (strexists ( $name, '/' )) {
		$tpl = "template/$name";
	} else {
		$tpl = "template/$name";
	}
	$objfile = S_ROOT . './data/tpl_cache/' . str_replace ( '/', '_', $tpl ) . '.php';
	if (! file_exists ( $objfile ) ||2>1) {
		include_once (S_ROOT . './source/function_template.php');
		parse_template ( $tpl );
	}
	
	return $objfile;
}

// 子模板更新检查
function subtplcheck($subfiles, $mktime, $tpl) {
	global $_SC, $_SCONFIG;
	
	if ($_SC ['tplrefresh'] && ($_SC ['tplrefresh'] == 1 || mt_rand ( 1, $_SC ['tplrefresh'] ) == 1)) {
		$subfiles = explode ( '|', $subfiles );
		foreach ( $subfiles as $subfile ) {
			$tplfile = S_ROOT . './template/' . $subfile . '.htm';
			@$submktime = filemtime ( $tplfile );
			if ($submktime > $mktime) {
				include_once (S_ROOT . './source/function_template.php');
				parse_template ( $tpl );
				break;
			}
		}
	}
}

function requestApi ($param) {
    global $_SC;
    $content = get_api_content($_SC['apiurl'], $param);
    $data = json_decode($content,true);
    return  $data['resultData'];
}

function get_url_param($param) {
	$arr = array ();
	foreach ( $param as $key => $val ) {
		$arr [] = $key . "=" . $val;
	}
	return implode ( "&", $arr );
}
function get_api_content($url, $param = array(), $token = '', $adminUid = 0) {
	global $_SC;
    if (empty($url)) $url = $_SC['apiurl'];
	$method     = 'GET';
	$timestamp  = time();
	$expires    = time() + 3600 * 24;
	if (empty($token)){
	    $token = $_SESSION['user']['token'];
	}
	if (empty($adminUid)){
	    $adminUid = $_SESSION['user']['adminUid'];
	}
	$arrContent = array(
            'uid'          =>    $adminUid,
            'timestamp'    =>    $timestamp,
            'expires'      =>    $expires
	);

	$sign = genSign($token, $method, $url, $arrContent);

	if (! empty ( $param )) {
		$pstr = get_url_param ( $param );
		$url = $url . '?' . $pstr;
	}
	$url .= '&timestamp='.$timestamp.'&expires='.$expires.'&adminUid='.$adminUid.'&signature='.$sign;
//echo "<pre>";print_r($url);die;
	return get_with_curl ( $url );
}
function get_with_curl($url) {
// 	check_login ();
	$cookie_file = S_ROOT . 'data/login_cookie.txt';
	$ch = curl_init ( $url );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt ( $ch, CURLOPT_BINARYTRANSFER, true );
	curl_setopt ( $ch, CURLOPT_COOKIEFILE, $cookie_file );
	curl_setopt ( $ch, CURLOPT_COOKIEJAR, $cookie_file );
	$output = curl_exec ( $ch );
	return $output;
}

function genSign($token, $method, $url, $arrContent) {
    $gather = $method.$url;
    ksort($arrContent);
    foreach($arrContent as $key => $value) {
        $gather .= $key.'='.$value;
    }
    $gather .= $token;
    $sign = md5(urlencode($gather));
    return $sign;
}

function get_login_admin() {
	$url = $_SC['apiurl']."?do=loginStatus&format=json";
	$content = get_api_content ( $url );
	return json_decode ( $content );
}
function check_login() {
	global $_SGLOBAL;
	$cookie_file = S_ROOT . 'data/login_cookie.txt';
	if (file_exists ( $cookie_file )) {
		$ftime = filemtime ( $cookie_file );
		if ($_SGLOBAL ['timestamp'] - $ftime < 600) {
			return true;
		}
	}
	$url = $_SC['apiurl'].'?account=xxttest001&passwd=1&do=adminLogin&format=json';
	$ch = curl_init ( $url );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt ( $ch, CURLOPT_BINARYTRANSFER, true );
	curl_setopt ( $ch, CURLOPT_COOKIEJAR, $cookie_file );
	curl_exec ( $ch );
	curl_close ( $ch );
	return true;
}

// 返回数据并转换结果
function requestAndResponse($url, $param){
    $content = get_api_content($url, $param);
    $content = json_decode($content, true);
    $result  = $content['resultData'];
    return $result;
}

//对象转换成数组
function object_to_array($obj) {
	$_arr = is_object ( $obj ) ? get_object_vars ( $obj ) : $obj;
	foreach ( $_arr as $key => $val ) {
		$val = (is_array ( $val ) || is_object ( $val )) ? object_to_array ( $val ) : $val;
		$arr [$key] = $val;
	}
	return $arr;
}

// 数组转换成对象
function array_to_object($d) {
	if (is_array ( $d )) {
		return ( object ) array_map ( __FUNCTION__, $d );
	} else {
		return $d;
	}
}
//去掉slassh
function sstripslashes($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = sstripslashes($val);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}

//获取字符串
function getstr($string, $length, $in_slashes=0, $out_slashes=0, $html=0) {
	global $_SC, $_SGLOBAL;

	$string = trim($string);
	$string = preg_replace("/\s*([\r\n]{1,})/",",", $string);
	if($in_slashes) {
		//传入的字符有slashes
		$string = sstripslashes($string);
	}
	if($html < 0) {
		//去掉html标签
		$string = preg_replace("/(\<[^\<]*\>|\r|\n|\s|\[.+?\])/is", ' ', $string);
		$string = shtmlspecialchars($string);
	} elseif ($html == 0) {
		//转换html标签
		$string = shtmlspecialchars($string);
	}
	if($length && strlen($string) > $length) {
		//截断字符
		$wordscut = '';
		if(strtolower($_SC['charset']) == 'utf-8') {
			//utf8编码
			$n = 0;
			$tn = 0;
			$noc = 0;
			while ($n < strlen($string)) {
				$t = ord($string[$n]);
				if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
					$tn = 1;
					$n++;
					$noc++;
				} elseif(194 <= $t && $t <= 223) {
					$tn = 2;
					$n += 2;
					$noc += 2;
				} elseif(224 <= $t && $t < 239) {
					$tn = 3;
					$n += 3;
					$noc += 2;
				} elseif(240 <= $t && $t <= 247) {
					$tn = 4;
					$n += 4;
					$noc += 2;
				} elseif(248 <= $t && $t <= 251) {
					$tn = 5;
					$n += 5;
					$noc += 2;
				} elseif($t == 252 || $t == 253) {
					$tn = 6;
					$n += 6;
					$noc += 2;
				} else {
					$n++;
				}
				if ($noc >= $length) {
					break;
				}
			}
			if ($noc > $length) {
				$n -= $tn;
			}
			$wordscut = substr($string, 0, $n);
		} else {
			for($i = 0; $i < $length - 1; $i++) {
				if(ord($string[$i]) > 127) {
					$wordscut .= $string[$i].$string[$i + 1];
					$i++;
				} else {
					$wordscut .= $string[$i];
				}
			}
		}
		$string = $wordscut;
	}
	if($out_slashes) {
		$string = saddslashes($string);
	}
	return trim($string);
}

// 时间格式化
function sgmdate($dateformat, $timestamp = '', $format = 0) {
	global $_SCONFIG, $_SGLOBAL;
	if (empty ( $timestamp )) {
		$timestamp = $_SGLOBAL ['timestamp'];
	}
	$timeoffset = 8;
	$result = gmdate ( $dateformat, $timestamp + $timeoffset * 3600 );
	return $result;
}

// 判断字符串是否存在
function strexists($haystack, $needle) {
	return ! (strpos ( $haystack, $needle ) === FALSE);
}

function getHashId($id, $baseNum, $code = NULL)
{
    $md5Id  =   md5($id);
    $decNum =   hexdec(substr($md5Id, -2));
    $result =   $decNum % $baseNum;
    return  $result;
}

//调整输出
function ob_out() {
	global $_SGLOBAL, $_SCONFIG, $_SC;

	$content = ob_get_contents();

	$preg_searchs = $preg_replaces = $str_searchs = $str_replaces = array();

	if($preg_searchs) {
		$content = preg_replace($preg_searchs, $preg_replaces, $content);
	}
	if($str_searchs) {
		$content = trim(str_replace($str_searchs, $str_replaces, $content));
	}

	obclean();
	if($_SCONFIG['headercharset']) {
		@header('Content-Type: text/html; charset='.$_SC['charset']);
	}
	echo $content;
	if(D_BUG) {
		//@include_once(S_ROOT.'./source/inc_debug.php');
	}
	
}

//ob
function obclean() {
	global $_SC;

	ob_end_clean();
	if ($_SC['gzipcompress'] && function_exists('ob_gzhandler')) {
		ob_start('ob_gzhandler');
	} else {
		ob_start();
	}
}

// 获取文件内容
function sreadfile($filename) {
	$content = '';
	if (function_exists ( 'file_get_contents' )) {
		@$content = file_get_contents ( $filename );
	} else {
		if (@$fp = fopen ( $filename, 'r' )) {
			@$content = fread ( $fp, filesize ( $filename ) );
			@fclose ( $fp );
		}
	}
	return $content;
}

// 写入文件
function swritefile($filename, $writetext, $openmod = 'w') {
	if (@$fp = fopen ( $filename, $openmod )) {
		flock ( $fp, 2 );
		fwrite ( $fp, $writetext );
		fclose ( $fp );
		return true;
	} else {
		runlog ( 'error', "File: $filename write error." );
		return false;
	}
}

// 写运行日志
function runlog($file, $log, $halt = 0) {
	global $_SGLOBAL, $_SERVER;
	
	$nowurl = $_SERVER ['REQUEST_URI'] ? $_SERVER ['REQUEST_URI'] : ($_SERVER ['PHP_SELF'] ? $_SERVER ['PHP_SELF'] : $_SERVER ['SCRIPT_NAME']);
	$log = sgmdate ( 'Y-m-d H:i:s', $_SGLOBAL ['timestamp'] ) . "\t$type\t" . "" . "\t$_SGLOBAL[supe_uid]\t{$nowurl}\t" . str_replace ( array (
			"\r",
			"\n" 
	), array (
			' ',
			' ' 
	), trim ( $log ) ) . "\n";
	$yearmonth = sgmdate ( 'Ym', $_SGLOBAL ['timestamp'] );
	$logdir = './data/log/';
	if (! is_dir ( $logdir ))
		mkdir ( $logdir, 0777 );
	$logfile = $logdir . $yearmonth . '_' . $file . '.php';
	if (@filesize ( $logfile ) > 2048000) {
		$dir = opendir ( $logdir );
		$length = strlen ( $file );
		$maxid = $id = 0;
		while ( $entry = readdir ( $dir ) ) {
			if (strexists ( $entry, $yearmonth . '_' . $file )) {
				$id = intval ( substr ( $entry, $length + 8, - 4 ) );
				$id > $maxid && $maxid = $id;
			}
		}
		closedir ( $dir );
		$logfilebak = $logdir . $yearmonth . '_' . $file . '_' . ($maxid + 1) . '.php';
		@rename ( $logfile, $logfilebak );
	}
	if ($fp = @fopen ( $logfile, 'a' )) {
		@flock ( $fp, 2 );
		fwrite ( $fp, "<?PHP exit;?>\t" . str_replace ( array (
				'<?',
				'?>',
				"\r",
				"\n" 
		), '', $log ) . "\n" );
		fclose ( $fp );
	}
	if ($halt)
		exit ();
}

function getHttpResponsePOST($url) {
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
    curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
    curl_setopt($curl, CURLOPT_USERAGENT, "FFWEB_1.0-API");
    curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_ENCODING, "");
    curl_setopt($curl, CURLOPT_HEADER, FALSE);
    $responseText = curl_exec($curl);

    // var_dump( curl_error($curl) );exit;//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
    curl_close($curl);
    return $responseText;
}

function parseData($result){
    return json_decode($result, true);
}

//urlencode
 function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            arrayRecursive($array[$key], $function, $apply_to_keys_also);
        } else {
            $array[$key] = $function($value);
        }

        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
}

 function JsonFormat($array) {
    arrayRecursive($array, 'urlencode', true);
    $json = json_encode($array);
    return urldecode($json);
}
//urlencode 只用于 一维数组
function JsonFormat_m($array){
    foreach ($array as $key => $value) {
        $arr[urlencode($key)]=urlencode($value);
    }
    return urldecode(json_encode($arr));
}

function var_json_encode($var) {
    $_var = var_urlencode($var);
    $_str = json_encode($_var);
    return urldecode($_str);
}

function var_urlencode($var) {
    if (empty ( $var )) {
        return false;
    }
    // 判断是否为数组
    if(is_array ($var)){
        foreach ($var as $k => $v ) {
            // is_scalar : 检测变量是否为标量
            if (is_scalar ($v)) {  // if用来处理不是数组的情况
                $var [$k] = urlencode ($v );
            }
            else {//else用来处理数组
                $var [$k] = var_urlencode ( $v );
            }
        }
    }else {//用来处理数组
        $var = urlencode ( $var );
    }
    return $var;
}

//一次性跳转
function showmessage($message, $url_forward='', $second=1, $values=array()) {
    global $_SGLOBAL, $_SC, $_SCONFIG, $_TPL, $space, $_SN;
    obclean();

    //显示
    if($url_forward && empty($second)) {
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: $url_forward");
    } else {
        //显示
        if($url_forward) {
             
            $message = "<a href=\"$url_forward\">$message</a><script>setTimeout(\"window.location.href ='$url_forward';\", ".($second*1000).");</script>";
        }

        include template('admin/showmessage');
    }
    exit();
}
//生成表情的预览图（动图和静图）
function gthumb($id,$ename,$thumbnail_m,$thumbnail_s){
    $baseUrl_s = $ename."_";
    $baseUrl_m = "http://d.fenfenriji.com/diary/emotion/".$id."/".$ename."/".$ename."_";

    // 处理预览图
    foreach ($thumbnail_m as $value){
        $thumbnail_m_arr[]   = mb_substr($value,strlen($baseUrl_m));
    }
    foreach ($thumbnail_s as $value){
        $thumbnail_s_arr[]   = mb_substr($value,strlen($baseUrl_s));
    }
    $thumbnail_m_str   = implode(',', $thumbnail_m_arr);
    $thumbnail_s_str   = implode(',', $thumbnail_s_arr);
    $result = array(
        's'=>$thumbnail_s_str,
        'm'=>$thumbnail_m_str
    );
    return $result;
}
function my_json_encode($in)/*{{{*/
{
	$_escape = function ($str) {
		return addcslashes($str, "\v\t\n\r\f\"\\/");
	};
	$out = "";
	if (is_object($in)) {
		$class_vars = get_object_vars(($in));
		$arr = array();
		foreach ($class_vars as $key => $val) {
			$arr[$key] = "\"{$_escape($key)}\":\"{$val}\"";
		}
		$val = implode(',', $arr);
		$out .= "{{$val}}";
	}elseif (is_array($in)) {
		$obj = false;
		$arr = array();
		foreach($in AS $key => $val) {
			if(!is_numeric($key)) {
				$obj = true;
			}
			$arr[$key] = my_json_encode($val);
		}
		if($obj) {
			foreach($arr AS $key => $val) {
				$arr[$key] = "\"{$_escape($key)}\":{$val}";
			}
			$val = implode(',', $arr);
			$out .= "{{$val}}";
		}else {
			$val = implode(',', $arr);
			$out .= "[{$val}]";
		}
	}elseif (is_bool($in)) {
		$out .= $in ? 'true' : 'false';
	}elseif (is_null($in)) {
		$out .= 'null';
	}elseif (is_string($in)) {
		$out .= "\"{$_escape($in)}\"";
	}else {
		$out .= $in;
	}
	return "{$out}";
}
function saveLog($fileName,$param,$dir='/tmp')
{
	$string = '['.date("Y/m/d").']:'.print_r($param,true)."\r\n";
	file_put_contents ($dir."/".$fileName.'.log', $string, FILE_APPEND);
}

function isMobile($phone)
{
	if(!preg_match("/^1[34578]\d{9}$/", $phone)){
		return false;
	}

	return true;
}
//表情包
function biaoqing_replace($content,$emotions = array()) {
    global $_SCONFIG, $_SGLOBAL;
    if(empty($_SGLOBAL['biaoqing'])){
        include_once (S_ROOT . './data/data_biaoqing.php');
    }
    if(empty($_SGLOBAL['bigbiaoqing'])){
        include_once (S_ROOT . './data/data_big_biaoqing.php');
    }
    $search = array();
    $replace = array();
    foreach ($_SGLOBAL['biaoqing'] as $key=>$val){
        $search[] = $key;
        $replace[] = '<img width="32" height="32" src="static_v2/img/emoji/'.$val.'">';
    }
    $content = str_replace ( $search, $replace, $content );
    if(!empty($emotions) && count($emotions)>0){
        $search = array();
        $replace = array();
        foreach ($emotions as $emotion){
            $search[] = strtoupper($emotion['ref']);
            if(isset($emotion['width']) && $emotion['width']>160){
                $emotion['width'] = 160;
            }
            $emotion['height'] = $emotion['width'];
            $replace[] = '<br/><img width="'.$emotion['width'].'" height="'.$emotion['height'].'" src="'.$emotion['src'].'" alt="'.$emotion['alt'].' title="'.$emotion['alt'].'"><br/>';
        }
        $content = str_replace ( $search, $replace, $content );
    }
    return $content;
}
?>